import urllib.parse as up
import urllib.request as ur
from get_url_response import geturl
import string

import json

if __name__ == '__main__':
    word = input('请输入要翻译的中文：')
    # word = '   你好'
    word = word.strip(" ")

    # word = '你好'
    data = {
        # 'from': 'zh',
        # 'to': 'en',
        # 'query': word,
        # 'token': 'a3ebfee20ffb3b086803a8f02391a980',
        'kw': word,
    }
    # headers = {
    #     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
    #     'Cookie': '',
    # }

    # print(data)
    data_url = up.urlencode(data)
    # print(data_url)

    # url = 'https://fanyi.baidu.com/v2transapi?from=zh&to=en'
    url = 'https://fanyi.baidu.com/sug'
    # print(data_url.encode('utf-8'))
    response = geturl(url,data=data_url.encode('utf-8'))
    # print(response)

    ret = json.loads(response)
    # translate = ret['trans_result']
    try:
        translate = ret['data'][0]['v']
        print('翻译结果：', translate)
    except:
        print('No results! Try another word.')